package com.zhou.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSONObject;
import com.zhou.cloud.entry.DemoHttpConst;
import com.zhou.cloud.entry.DemoHttpRespStatus;
import com.zhou.cloud.service.IGeneratorUuidService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author zhouyongjun
 * @Description:
 * @date 2021/4/6 16:45
 */
@RestController
@RequestMapping("uuid")
@Slf4j
public class UuidController {
    @Autowired
    @Qualifier("redisUuidService")
    IGeneratorUuidService redisUuidService;

    @Resource(name="snowflakeUuidService")
    IGeneratorUuidService snowflakeUuidService;
    /**
    * @Description: 生成uuid,默认使用redis方式
    * @Params:
    * @Returns:
    * @Author: zhouyongjun
    * @Date Created in 2022/11/4 9:20
     */
    @GetMapping("/generator")
    @SentinelResource(value = "generator-default",fallback = "generatorFailBack",blockHandler = "generatorFailBack")
    public JSONObject generator() {
        return generatorUuidByRedis();
    }

    /**
    * @Description: redis方式生成uuid
    * @Params:
    * @Returns:
    * @Author: zhouyongjun
    * @Date Created in 2022/11/4 9:20
     */
    @GetMapping("/generator/redis")
    @SentinelResource(value = "generator-redis",fallback = "generatorFailBack",blockHandler = "generatorFailBack")
    public JSONObject generatorUuidByRedis() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(DemoHttpConst.RESP_CODE, DemoHttpRespStatus.OK);
        jsonObject.put(DemoHttpConst.RESP_UUID,redisUuidService.generatorUuid());
        return jsonObject;
    }

    /**
    * @Description: snowflake方式生成uuid
    * @Params: 
    * @Returns: 
    * @Author: zhouyongjun
    * @Date Created in 2022/11/4 9:21
     */
    @GetMapping("/generator/snowflake")
    @SentinelResource(value = "generator-snowflake",fallback = "generatorFailBack",blockHandler = "generatorFailBack")
    public JSONObject generatorUuidBySnowflake() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uuid",snowflakeUuidService.generatorUuid());
        return jsonObject;
    }

    public JSONObject generatorFailBack(Throwable e) {
        log.error("",e);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(DemoHttpConst.RESP_CODE, DemoHttpRespStatus.FAIL);
        jsonObject.put(DemoHttpConst.RESP_MSG,"uuid生成失败");
        return jsonObject;
    }

}
